package server.business.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class JdbcUtils {
    private static DruidDataSource dataSource;
    static {//连接池建立
        try {
            Properties properties = new Properties();
            InputStream inputestream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(inputestream);
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
//            System.out.println(dataSource.getConnection());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 获取数据库连接池的链接
     * @return如果返回null说明失败</br>有值就说明陈工
     */

    public  static Connection getConnection(){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
//            System.out.println("数据库连接成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }


        return conn;

    }

    /**
     * 关闭连接
     * @param conn
     */
    public static void close(Connection conn){
        if(conn != null){
            try {
                conn.close();
//                System.out.println("数据库释放成功");
            } catch (Exception throwables) {
                throwables.printStackTrace();
                System.out.println("数据库释放失败");
            }
        }
    }

}
